from docx.document import Document
from docx.oxml.table import CT_Tbl
from docx.oxml.text.paragraph import CT_P
from docx.table import _Cell, Table
from docx.text.paragraph import Paragraph
import docx
import os, re


def iter_block_items(parent):
    """
    Yield each paragraph and table child within *parent*, in document order.
    Each returned value is an instance of either Table or Paragraph. *parent*
    would most commonly be a reference to a main Document object, but
    also works for a _Cell object, which itself can contain paragraphs and tables.
    """
    if isinstance(parent, Document):
        parent_elm = parent.element.body
    elif isinstance(parent, _Cell):
        parent_elm = parent._tc
    else:
        raise ValueError("something's not right")

    for child in parent_elm.iterchildren():
        if isinstance(child, CT_P):
            yield Paragraph(child, parent)
        elif isinstance(child, CT_Tbl):
            yield Table(child, parent)


def get_pictures(doc, result_path):
    """
    图片提取
    :param word_path: word路径
    :return:
    """
    try:
        dict_rel = doc.part._rels
        for rel in dict_rel:
            rel = dict_rel[rel]
            if "image" in rel.target_ref:
                if not os.path.exists(result_path):
                    os.makedirs(result_path)
                img_name = re.findall("/(.*)", rel.target_ref)[0]
                with open(os.path.join(result_path, img_name), "wb") as f:
                    f.write(rel.target_part.blob)
        reformat_pictures(result_path)
    except:
        pass


def reformat_pictures(result_path):
    """
    图片格式转换为jpeg
    :param result_path:
    :return:
    """

    from wand.image import Image
    for root, dirs, files in os.walk(result_path):
        for file in files:
            file_path = os.path.join(root, file)
            new_file_path = os.path.join(root, F'{file.split(".")[0]}.jpeg')
            if file.endswith('emf'):
                with Image(filename=file_path) as img:
                    img.format = 'jpeg'
                    img.save(filename=new_file_path)

                os.remove(file_path)
